package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebFilter(urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器用于类的匹配，三个关键字表示公开静态的不可修饰对象
    public static final AntPathMatcher pathMatcher=new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        String requestURI=request.getRequestURI();

       /* String servletPath = request.getServletPath();
        String serverName = request.getServerName();
        if (!serverName.contains("localhost")){
            log.info(request.getRemoteAddr());
            if (servletPath.contains("/backend/myself/Myself.html")
                    ||servletPath.contains("/backend/myself/1.jpg")
            ){
                filterChain.doFilter(request, response);
                return;
            }
            response.sendRedirect(request.getContextPath()+"/backend/myself/Myself.html");
            return;
        }*/
        String[] urls=new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };
        boolean check=check(urls,requestURI);
        if(check){
            filterChain.doFilter(request, response);
            return;
        }
        Long e =(Long)request.getSession().getAttribute("employee");
        if (e!=null){
            BaseContext.setCurrentId(e);
            filterChain.doFilter(request, response);
            return;
        }
        Long u =(Long)request.getSession().getAttribute("userId");
        if (u!=null){
            BaseContext.setCurrentId(u);
            filterChain.doFilter(request, response);
            return;
        }
        log.info("请先登录!");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;


    }
    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = pathMatcher.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }
}

